import Card from '@/components/Card';
import { MyChartOption } from '@/components/EchartsComponent';
import Empty from '@/components/Empty';
import HealthReport from '@/components/HealthReport';
import { ProForm, ProFormDateRangePicker } from '@/components/Pro';
import BatteryBarChart from '@/pages/BatteryHealthEvaluate/Capacity/components/BatteryBarChart';
import { sohControllerGetData2, sohControllerSyncSoh } from '@/services/ess/healthSoh';
import { useModel } from '@@/exports';
import { useIntl } from '@umijs/max';
import { Button, DatePicker, Flex, GetProps, message, Modal, Space } from 'antd';
import cls from 'classnames';
import dayjs from 'dayjs';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import StandText from './components/StandText';
import Styles from './index.less';

type PieChartProps = {
  options: MyChartOption;
  pieInfo: API.PieData;
};
type RangePickerProps = GetProps<typeof DatePicker.RangePicker>;
const Capacity: React.FC = () => {
  const intl = useIntl();
  const { stationId } = useModel('@@initialState')?.initialState || {};
  const [pageData, setPageData] = useState<API.SohData>({});
  const [modalDate, setModalDate] = useState<[string, string]>([
    dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
    dayjs().format('YYYY-MM-DD'),
  ]);
  const [pieChartOptions, setPieChartOptions] = useState<PieChartProps>();
  const modalFormRef = useRef();
  const [isShowSOHModal, setIsShowSOHModal] = useState(false);
  const [remark, setRemark] = useState();
  const [suggest, setSuggest] = useState();

  const [boxArray, setBoxArray] = useState<API.BmsSoh[]>([]);
  const getSocContent = () => {
    sohControllerGetData2({ stationId: stationId }).then((res) => {
      const data = res.data ?? {};
      setBoxArray(data.bmsList ?? []);
      setRemark(data.remark);
      setSuggest(data.suggest);
      setPageData(data ?? {});
      const { pie } = data;
      setPieChartOptions({
        options: {
          tooltip: { trigger: 'item' },
          series: [
            {
              type: 'pie',
              radius: ['50%', '70%'],
              label: { show: false },
              data: [
                {
                  value: pie?.a,
                  name: '90% <SOH ≤100%',
                  itemStyle: {
                    color: '#F0F1F5',
                  },
                },
                {
                  value: pie?.b,
                  name: '80% <SOH ≤90%',
                  itemStyle: {
                    color: '#FFD60C',
                  },
                },
                {
                  value: pie?.c,
                  name: '70% <SOH ≤80%',
                  itemStyle: {
                    color: '#FF790D',
                  },
                },
                {
                  value: pie?.d,
                  name: '60% <SOH ≤70%',
                  itemStyle: {
                    color: '#FF5353',
                  },
                },
                {
                  value: pie?.e,
                  name: 'SOH ≤60%',
                  itemStyle: {
                    color: '#3586FF',
                  },
                },
              ],
            },
          ],
        },
        pieInfo: pie,
      });
    });
  };
  const disabledDate: RangePickerProps['disabledDate'] = (current, { from }) => {
    // Can not select days before today and today
    if (from) {
      return Math.abs(current.diff(from, 'month')) >= 1 || current > dayjs().endOf('day');
    }
    return current && current > dayjs().endOf('day');
  };
  useEffect(() => {
    getSocContent();
    return () => {};
  }, []);
  const validator = (_: any, value) => {
    if (!value || !value[0] || !value[1]) {
      return Promise.resolve();
    }

    if (value[1].diff(value[0], 'days') > 30) {
      return Promise.reject(new Error(intl.formatMessage({ id: 'batteryVoltage.exceed30' })));
    }

    return Promise.resolve();
  };
  return (
    <div>
      <Card style={{ paddingTop: 15, paddingBottom: 15 }}>
        <Flex justify="space-between">
          <Space>
            <div style={{ maxWidth: 510, marginRight: 20 }}>
              {intl.formatMessage({ id: 'batteryVoltage.capacity.time' })}：
              {pageData?.createDate ? (
                <>
                  {pageData?.createDate}
                  {intl.formatMessage({ id: 'batteryVoltage.safe.cycle' })}
                  {pageData?.startDate}
                  {intl.formatMessage({ id: 'batteryVoltage.vol.to' })}
                  {pageData?.endDate}
                  {intl.formatMessage({ id: 'batteryVoltage.resultAuto' })}
                  {pageData?.createDate?.substring(0, 7)}
                  {intl.formatMessage({ id: 'batteryVoltage.monthReport' })}
                </>
              ) : (
                <>{intl.formatMessage({ id: 'batteryVoltage.tips.none' })}</>
              )}
            </div>
            <Button
              type="primary"
              onClick={() => {
                setIsShowSOHModal(true);
              }}
            >
              {intl.formatMessage({ id: 'batteryVoltage.capacity.update' })}
            </Button>
          </Space>
          <div>
            <HealthReport date={moment().format('YYYY-MM-DD')} />
          </div>
        </Flex>
      </Card>
      <Flex style={{ marginTop: '20px' }} gap={20}>
        <Card
          title={intl.formatMessage({ id: 'batteryVoltage.capacity.sumTable' })}
          extra={<StandText key="stand" />}
          style={{ flex: 2, paddingTop: '20px' }}
        >
          {boxArray?.length ? (
            <>
              <div className={Styles['content-left']}>
                {boxArray.map((item: API.BmsSoh, index) => {
                  return (
                    <div
                      key={index}
                      className={cls([Styles['content-box-blank']], {
                        [Styles['content-box-blank']]: item?.soh > 90 && item?.soh <= 100,
                        [Styles['content-box-orange']]: item?.soh > 80 && item?.soh <= 90,
                        [Styles['content-box-yellow']]: item?.soh > 70 && item?.soh <= 80,
                        [Styles['content-box-red']]: item?.soh > 60 && item?.soh <= 70,
                        [Styles['content-box-blue']]: item?.soh <= 60,
                      })}
                    >
                      <div style={{ fontSize: '16px', color: '#222' }}>{item.name}</div>
                      <div style={{ fontSize: '12px', color: '#222' }}>
                        {intl.formatMessage({ id: 'batteryVoltage.vol.cc' })} {item.residueCapacity}
                        kWh
                      </div>
                      <div style={{ fontSize: '12px', color: '#222' }}>
                        {intl.formatMessage({ id: 'batteryVoltage.vol.cc' })} {item.ratedCapacity}
                        kWh
                      </div>
                      <div style={{ fontSize: '12px', color: '#222' }}>SOH {item.soh}%</div>
                    </div>
                  );
                })}
              </div>
              <div style={{ marginTop: 20 }}>
                {' '}
                {intl.formatMessage({ id: 'batteryVoltage.tips.socFor' })}：{remark}
              </div>
              <div>
                {intl.formatMessage({ id: 'batteryVoltage.suggestions' })}：
                {suggest || intl.formatMessage({ id: 'batteryVoltage.vol.suggestions' })}
              </div>
            </>
          ) : (
            <Flex justify="center" align="center" style={{ height: 300 }}>
              <Empty />
            </Flex>
          )}
        </Card>
        <Card
          title={intl.formatMessage({ id: 'batteryVoltage.capacity.rate' })}
          style={{ flex: 1, paddingTop: '20px' }}
        >
          {pageData?.pie ? (
            <div className={Styles['content-right']}>
              <BatteryBarChart pieChartOptions={pieChartOptions} />
            </div>
          ) : (
            <Flex justify="center" align="center" style={{ height: 300 }}>
              <Empty />
            </Flex>
          )}
        </Card>
      </Flex>
      <Modal
        title={intl.formatMessage({ id: 'batteryVoltage.tips.SOH' })}
        open={isShowSOHModal}
        onCancel={() => {
          setIsShowSOHModal(false);
        }}
        footer={() => (
          <Flex style={{ gap: '20px' }}>
            <Button
              type={'primary'}
              onClick={() => {
                modalFormRef?.current
                  .validateFields()
                  .then(() => {
                    const params: API.SyncSohReq = {
                      stationId: stationId,
                      startDate: modalDate[0],
                      endDate: modalDate[1],
                    };
                    sohControllerSyncSoh(params).then((res) => {
                      if (res.data) {
                        message.success(intl.formatMessage({ id: 'batteryVoltagevol.updateSOC' }));
                        setIsShowSOHModal(false);
                        getSocContent();
                      } else {
                        message.info(intl.formatMessage({ id: 'batteryVoltagevol.tips' }));
                        setIsShowSOHModal(false);
                      }
                    });
                  })
                  .catch((err) => {
                    console.log('error', err);
                  });
              }}
            >
              {intl.formatMessage({ id: 'batteryVoltage.tips.update' })}
            </Button>
            <Button
              onClick={() => {
                setIsShowSOHModal(false);
              }}
            >
              {intl.formatMessage({ id: 'batteryVoltage.cancel' })}
            </Button>
          </Flex>
        )}
      >
        <div className={Styles.ModalTitle}>
          {intl.formatMessage({ id: 'batteryVoltage.tips.sys' })}
        </div>
        <ProForm submitter={false} layout={'inline'} formRef={modalFormRef}>
          <ProForm.Item
            label={intl.formatMessage({ id: 'batteryVoltage.tips.maintain' })}
            name={'timeVal'}
            rules={[
              {
                validator: validator,
              },
            ]}
          >
            <ProFormDateRangePicker
              fieldProps={{
                disabledDate: disabledDate,
                defaultValue: [dayjs().subtract(7, 'day'), dayjs()],
                onCalendarChange: (e, value, range) => {
                  if (range.range === 'end') {
                    setModalDate(value);
                  }
                },
              }}
            ></ProFormDateRangePicker>
          </ProForm.Item>
        </ProForm>
      </Modal>
    </div>
  );
};

export default Capacity;
